#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LLM分析器演示脚本
展示如何使用LLM分析器处理不同类型的异常
"""

import asyncio
import os
import sys
from datetime import datetime

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from agent_mcp.llm.llm_analyzer import LLMAnalyzer

async def demo_llm_analyzer():
    """演示LLM分析器功能"""
    
    print("=== LLM分析器演示 ===")
    print("本演示将展示如何处理不同类型的系统异常\n")
    
    # 初始化LLM分析器
    llm_analyzer = LLMAnalyzer(confidence_threshold=0.8)
    
    # 创建Ansible目录
    ansible_dir = "agent-mcp/Ansible"
    os.makedirs(ansible_dir, exist_ok=True)
    
    # 定义不同类型的异常测试数据
    test_anomalies = [
        {
            "name": "CPU使用率异常",
            "data": {
                "anomaly_id": "cpu_001",
                "issue_type": "cpu_usage",
                "root_cause": "cpu usage spike due to high load",
                "severity": 8,
                "contributing_factors": ["high concurrent users", "inefficient queries"],
                "evidence": ["cpu usage 95%", "load average 15.2", "response time increased"]
            }
        },
        {
            "name": "内存泄漏异常",
            "data": {
                "anomaly_id": "mem_001",
                "issue_type": "memory_leak",
                "root_cause": "memory leak in application process",
                "severity": 7,
                "contributing_factors": ["application bug", "unreleased memory"],
                "evidence": ["memory usage 85%", "swap usage increased", "oom killer triggered"]
            }
        },
        {
            "name": "磁盘IO异常",
            "data": {
                "anomaly_id": "disk_001",
                "issue_type": "disk_io",
                "root_cause": "high disk io due to database operations",
                "severity": 6,
                "contributing_factors": ["large database queries", "insufficient indexing"],
                "evidence": ["disk io wait 25%", "iostat shows high utilization"]
            }
        },
        {
            "name": "网络延迟异常",
            "data": {
                "anomaly_id": "net_001",
                "issue_type": "network_issue",
                "root_cause": "network latency spike",
                "severity": 5,
                "contributing_factors": ["network congestion", "packet loss"],
                "evidence": ["ping latency 200ms", "packet loss 5%"]
            }
        },
        {
            "name": "进程异常",
            "data": {
                "anomaly_id": "proc_001",
                "issue_type": "process_issue",
                "root_cause": "zombie processes accumulation",
                "severity": 4,
                "contributing_factors": ["parent process not waiting", "signal handling issue"],
                "evidence": ["zombie processes count 15", "process table full"]
            }
        }
    ]
    
    # 处理每个异常
    for i, anomaly_info in enumerate(test_anomalies, 1):
        print(f"\n--- 测试 {i}: {anomaly_info['name']} ---")
        
        anomaly_data = anomaly_info['data']
        
        # 获取置信度信息
        confidence_info = llm_analyzer.get_confidence_info(anomaly_data)
        
        print(f"异常ID: {anomaly_data['anomaly_id']}")
        print(f"问题类型: {anomaly_data['issue_type']}")
        print(f"根本原因: {anomaly_data['root_cause']}")
        print(f"严重程度: {anomaly_data['severity']}")
        print(f"置信度分数: {confidence_info['confidence_score']:.3f}")
        print(f"置信度等级: {confidence_info['confidence_level']}")
        
        # 处理异常
        try:
            result = await llm_analyzer.process_anomaly(anomaly_data, ansible_dir)
            
            if result['success']:
                print(f"✅ 使用LLM分析处理成功")
                print(f"   生成的脚本: {result.get('generated_script', 'N/A')}")
                print(f"   异常类型: {result.get('anomaly_type', 'N/A')}")
            else:
                print(f"❌ 处理失败: {result.get('error', '未知错误')}")
                
        except Exception as e:
            print(f"❌ 处理异常时出错: {e}")
        
        print("-" * 50)
    
    print("\n=== 演示完成 ===")
    print(f"所有生成的脚本都保存在: {ansible_dir}")
    print("请检查生成的脚本文件以验证LLM分析器的功能。")

def show_usage_example():
    """显示使用示例"""
    print("\n=== 使用示例 ===")
    print("""
# 基本使用
llm_analyzer = LLMAnalyzer(confidence_threshold=0.8)

# 处理异常
result = await llm_analyzer.process_anomaly(anomaly_data, ansible_dir)

# 获取置信度信息
confidence_info = llm_analyzer.get_confidence_info(anomaly_data)
print(f"置信度: {confidence_info['confidence_score']}")
print(f"需要LLM: {confidence_info['needs_llm']}")
""")

if __name__ == "__main__":
    # 显示使用示例
    show_usage_example()
    
    # 运行演示
    asyncio.run(demo_llm_analyzer()) 